<?php
namespace App\Http\Controllers\Company;

use App\Http\Controllers\Controller;
use App\Models\Area;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\DB;
use App\Models\CompanyJobsType;
use App\User;
/**
 *
 * @author Joker
 *        
 */
class CompanyController extends Controller
{
    protected  $_date = [];
    
    protected  $uid;
    
    /**
     * @var gzxz  工作性质字典
     * 工作性质  0 全职， 1 兼职 ， 2 实习 ，默认0 全职
     */
    protected $gzxz = array();
    
    /**
     * @var salary 薪资 字典
     * 薪资 0:2k以下；1：2k-5K；2：5k-10k; 3:10k-15k; 4:15k-25k; 5:25k-50k; 6:50k以上 默认0
    */
    protected $salary = array();
    
    /**
     * @var degree 学历
     * 0：大专；1本科；2:硕士；3：博士；4其它； 默认0
    */
    protected $degree = array();
    
    /**
     * @var gznx 工作年限
     * 工作年限 0 应届毕业生 1：1年 ； 2：2年 。。。。10：年  ； >10 为10年以上
    */
    protected $gznx = array();
    
    /**
     * @var status 职位状态 0 未审核  1:审核通过 2:审核不通过; 3:关闭
    */
    protected $status = array();
    
    protected $area;
    
    protected $userinfo;
    
    public function __construct()
    {
        $this->middleware('auth');
        $this->middleware('company');
        $this->uid = Auth::user()->id;
        $this->userinfo = User::find($this->uid);
        $this->nav = 1;
        $this->_date = [
            'today'      => '今天',
            'yesterday'  => '昨天',
            'this_week'  => '本周',
            'last_week'  => '上周',
            'all'        => '全部'
        ];
        $this->gzxz = array(0=>'全职',1=>'兼职',2=>'实习');
        $this->salary = array(0=>'2k以下',1=>'2k~5k',2=>'5k~10k',3=>'10k~15k',4=>'15k~25k',5=>'25k~50k',6=>'50k以上');
        $this->gznx = array(0=>'应届毕业生',1=>'1年以下',2=>'1-3年',3=>'3-5年',4=>'5-10年',5=>'10年以上',100=>'不限');
        $this->degree = array(0=>'大专',1=>'本科',2=>'硕士',3=>'博士',4=>'其他',100=>'不限');
        $this->status = array(0=>'未审核',1=>'审核通过',2=>'审核不通过',3=>'关闭');
        $this->area= Area::where('pid','=',0)->orderBy('sort','ASC')->get();
    }
    
    
    /**
     * 企业中心首页
     * @return [type] [description]
     */
    public function index()
    {
        if(empty($this->userinfo->company_id))
            return redirect(url('/company/center/companyinfo-default'));
        
        $tab_arr = ['company_jobs', 'company_folder', 'company_comment', 'inbox'];
        $total_array = [
            'today' => $this->getTotalByDate(
                $tab_arr,
                'today',
                $this->uid
            ),
            'yesterday' => $this->getTotalByDate(
                $tab_arr,
                'yesterday',
                $this->uid
            ),
            'this_week' => $this->getTotalByDate(
                $tab_arr,
                'this_week',
                $this->uid
            ),
            'last_week' => $this->getTotalByDate(
                $tab_arr,
                'last_week',
                $this->uid
            ),
            'all' => [0,0,0,0]
        ];
        for ($i=0; $i < 4; $i++) {
            foreach ($total_array as $value) {
                $total_array['all'][$i] += $value[$i];
            }
        }
        return view('company.index')
            ->with('total_arr', $total_array)
            ->with('date_array', $this->_date);
    }
    
    /**
     * @param string $status
     * @param string $msg
     * @param array $data
     * @param string $redirectUrl
     */
    public function formatJson($status='success',$msg='没有更多数据',$data=array(),$redirectUrl = '')
    {
        $result = array(
            'status'        => $status,
            'msg'           => $msg,
            'data'          => $data,
            'redirectUrl'   => $redirectUrl
        );
        return Response::json($result);
    }
    
    /**
     * 根据日期统计个数
     * @param  string $table [description]
     * @param  string $date  [description]
     * @return [array]        [description]
     */
    public function getTotalByDate($tables = [], $date = 'today', $company_id = 0)
    {
        $where = '';
        switch ($date) {
            case 'today':  //今天
                $where .= ' WHERE DATE(created_at)=CURDATE()';
                break;
            case 'yesterday':  //昨天
                $where .= ' WHERE DATE(created_at)=DATE_SUB(CURDATE(),INTERVAL 1 DAY)';
                break;
            case 'this_week':  //这周
                $where .= ' WHERE YEARWEEK(created_at) = YEARWEEK(NOW())';
                break;
            case 'last_week':  // 上周
                $where .= ' WHERE YEARWEEK(created_at) = YEARWEEK(NOW())-1';
                break;
    
            default:
                # code...
                break;
        }
        $reult = [];
        if(is_array($tables) AND !empty($tables)) {
            foreach ($tables as $table) {
                $and_where = '';
                if($table == 'inbox')
                    $and_where .= ' AND user_id=' . $company_id;
                else
                    $and_where .= ' AND company_id=' . $company_id;
    
                $sql = 'SELECT COUNT(*) AS total FROM qm_' . $table . $where . $and_where;
                $reult[] = DB::select($sql)[0]->total;
            }
        }
        return $reult;
    }
    
    /**
     * 获取分类下拉菜单
     * @param int $selectid
     * @param bool $use_ext   是否使用mobile_catalog表，扩展分类信息
     * @return string
     */
    protected function getJobsTypeOptions($selectid = 0)
    {
        $cate_tree = $this->getJobsTypeTree(0, false, 1);
        $options = '<option value="0">----无----</option>';
        foreach ($cate_tree as $cat) {
            //            if ($cat['disabled'] == 1) continue; //该分类被禁用
            if ($selectid > 0 && $selectid == $cat['id']) {
                $selected = 'selected="true"';
            } else {
                $selected = '';
            }
            if ($cat['depath'] == 1) {
                $options .= sprintf('<option value="%d" %s>├ %s</option>', $cat['id'], $selected, $cat['name']);
            } else {
                $options .= sprintf('<option value="%d" %s>%s├ %s</option>', $cat['id'], $selected,
                    str_repeat('&nbsp;', $cat['depath'] * 2), $cat['name']);
            }
        }
        return $options;
    }
    
    /**
     * xiadx
     * 获得指定分类同级的所有分类，以及该分类下的子分类
     * @param int $cat_id        分类编号
     * @param bool $is_samelv     是否显示同级分类，默认false
     * @param int   $ret_depath   返回的数组类型，1是一维数组，其它则为多维数组
     * @return array
     */
    protected function getJobsTypeTree($cat_id = 0, $is_samelv = false, $ret_depath = 1)
    {
        static $depath = 0; //层级
    
        if ($is_samelv === true) {
            // 获得指定分类同级的所有分类
            if ($cat_id > 0) {
                $mod_cat = CompanyJobsType::where(['cat_id' => $cat_id, 'display' =>0])->first();
                $parent_id = $mod_cat->parent_id;
            } else {
                //顶级分类，获取所有分类->cached()
                $parent_id = 0;
            }
        } else {
            $parent_id = $cat_id; //获取指定分类下的子分类
        }
    
        $total = CompanyJobsType::where(['parent_id' => $parent_id, 'display' => 0])->count();
    
        $cat_array =  array();
        if ($total > 0 || $parent_id == 0) {
            $data = CompanyJobsType::where(['parent_id' => $parent_id, 'display' => 0])
            ->get();
            //加一层
            ++$depath;
            foreach ($data AS $k => $row) {
                $cat_array[] = array(
                    'id' => $row->cat_id,
                    'name' => $row->name,
                    'pid' => $row->parent_id,
                    'ordernum' => $row->sort,
                    'depath' => $depath,
                    'child_num' => 0
                );
                $cid = $row->cat_id;
                $key = count($data) - 1;
                if ($ret_depath > 1) {
    
                    //递归，获取子分类
                    $child = $this->getJobsTypeTree($cid, $is_samelv, $ret_depath);
    
                    if (count($child > 0)) {
                        $cat_array[$k]['child'] = $child;
                        $cat_array[$k]['child_num'] = count($child);
                    }
                } else {
                    //递归，获取子分类
                    $child = $this->getJobsTypeTree($cid, $is_samelv, $ret_depath);
    
                    if (count($child)) {
                        foreach ($child as $sub) {
                            $cat_array[] = $sub;
                        }
                    }
                }
            }
            //减一层
            --$depath;
        }
        return $cat_array;
    }
}